package com.pandas.community.service;

import com.pandas.community.Utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class LikeService {
    @Autowired
    private RedisTemplate redisTemplate;

    // 点赞
    public void like(int userid, int entityType, int entityId, int entityUserid){
//        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
//        if(redisTemplate.opsForSet().isMember(entityLikeKey, userid)){
//            redisTemplate.opsForSet().remove(entityLikeKey, userid);
//        }else{
//            redisTemplate.opsForSet().add(entityLikeKey, userid);
//        }

        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserid);
                boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userid);

                //开启事务前先查询
                redisTemplate.multi();
                if(isMember){
                    redisOperations.opsForSet().remove(entityLikeKey, userid);
                    redisOperations.opsForValue().decrement(userLikeKey);
                }else{
                    redisOperations.opsForSet().add(entityLikeKey, userid);
                    redisOperations.opsForValue().increment(userLikeKey);
                }
                return redisTemplate.exec();
            }
        });
    }

    // 查询某实体的被点赞的总数
    public long getEntityLikeCount(int entityType, int entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }

    //查询某人对某实体的点赞状态
    public int getEntityLikeStatus(int userid, int entityType, int entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        //1 点赞 0 未赞
        return redisTemplate.opsForSet().isMember(entityLikeKey, userid) ? 1 : 0;
    }

    //查询某人的被点赞数
    public int getUserLikeStatus(int entityUserid){
        String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserid);
        Integer userLikeCount = (Integer) redisTemplate.opsForValue().get(userLikeKey);
        return userLikeCount == null ? 0 : userLikeCount;
    }

}
